from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import status
from rest_framework.generics import ListAPIView, UpdateAPIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from goods.models import SKUImage, SKU
from meiduo_admin.good.order_serializsers import OrderStatusSerializser
from meiduo_admin.good.sku_images_serializers import SKUImagesSerializer, SKUInfoSerializser
from meiduo_admin.my_paginate import MyPageNumberPagination
from orders.models import OrderInfo


class SKUImagesViewSet(ModelViewSet):
    pagination_class = MyPageNumberPagination
    serializer_class = SKUImagesSerializer
    queryset = SKUImage.objects.all()

    def create(self, request, *args, **kwargs):
        # 1.接收数据
        sku_id = request.data.get('sku')
        image = request.FILES.get('image')
        # 2.检验数据
        if not all([sku_id, image]):
            return Response('参数不全', status=400)
        # 3.上传图片
        client = Fdfs_client(settings.CONFIG_URL)
        result = client.upload_by_buffer(image.read())
        if result['Status'] != 'Upload successed.':
            return Response('上传失败', status=400)
        # 4.返回响应
        image_url = result['Remote file_id']
        SKUImage.objects.create(sku_id=sku_id, image=image_url)
        SKU.objects.filter(id=sku_id, default_image_url='').update(default_image_url=image_url)
        return Response(status=status.HTTP_201_CREATED)

    def update(self, request, *args, **kwargs):
        # 1.接收数据
        sku_id = request.data.get('sku')
        image = request.data.get('image')
        sku_image = self.get_object()
        # 2.检验数据

        if not all([sku_id, image]):
            return Response('参数不全', status=400)
        # 3.上传图片
        client = Fdfs_client(settings.CONFIG_URL)
        result = client.upload_by_buffer(image.read())
        if result['Status'] != 'Upload successed.':
            return Response('上传失败', status=400)
        # 4.返回响应
        image_url = result['Remote file_id']
        SKUImage.objects.filter(id=sku_image.id, sku_id=sku_id).update(image=image_url)
        # SKU.objects.filter(id=sku_id, default_image_url='').update(default_image_url=image_url)
        return Response(status=status.HTTP_201_CREATED)


class SKUInfoListView(ListAPIView):
    serializer_class = SKUInfoSerializser
    queryset = SKU.objects.all()


class OrderStatusView(UpdateAPIView):
    queryset = OrderInfo.objects.all()
    serializer_class = OrderStatusSerializser
